import json
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import subprocess

'''
# 配置文件说明
# start_maximized = 启动直接最大化浏览器窗口,
# start_maximized = 启动直接全屏浏览器窗口,
# chrome_driver_path = chromedriver路径,
# login_auto = 开启自动登录,
# url = 浏览器访问地址,
# username = 账号,
# password = 密码,
'''

# 读取配置文件
with open('config.json', 'r', encoding='gbk') as config_file:
    config = json.load(config_file)

options = Options()

if config["start_maximized"]:
    options.add_argument("--start-maximized")  # 启动浏览器时自动最大化窗口
if config["start_fullscreen"]:
    options.add_argument("--start-fullscreen")  # 启动浏览器后直接全屏窗口
options.add_experimental_option('excludeSwitches', ['enable-automation'])   # 关闭提示
options.add_argument("--disable-save-password-bubble")  # 禁用自动保存密码提示
options.add_argument("--password-store=basic")      # 禁用自动保存密码提示
options.add_argument("--password-manager-enabled=false")    # 禁用自动保存密码提示
options.add_argument("--kiosk-printing")        # 不显示打印预览

options.add_experimental_option('prefs', {'credentials_enable_service': False, 'profile.password_manager_enabled': False})      # 禁用自动保存密码提示
options.add_experimental_option('detach', True)  # 执行完不关闭窗口


# 隐藏 chrome_driver 命令行窗口
chrome_process = subprocess.Popen(config["chrome_driver_path"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess.DETACHED_PROCESS)

# 读取配置文件中的 chrome_driver 路径
# py39
# driver = webdriver.Chrome(service=Service(config["chrome_driver_path"]), options=options)  # 请将路径替换为你的chromedriver.exe所在路径

# py37
driver = webdriver.Chrome(executable_path=config["chrome_driver_path"], options=options)

# 读取配置文件中的 url 路径
driver.get(config["url"])  # 打开网页

# 通过id定位用户名和密码框并输入对应的用户名和密码
username = driver.find_element(By.ID, 'username')
password = driver.find_element(By.ID, 'password')

# 读取配置文件中的账号和密码
if config["login_auto"]:
    username.send_keys(config["username"])
    password.send_keys(config["password"])

    # 定位到登录按钮并点击
    login = driver.find_element(By.ID, 'login')
    login.click()

    # 浏览器缩放
    window_zoom_percent = config["chrome_zoom"]
    driver.execute_script("document.body.style.zoom='{}%'".format(window_zoom_percent))
